package org.ezplatform.office.forum.web.rest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.forum.entity.ForumLabel;
import org.ezplatform.office.forum.entity.ForumModeratorScope;
import org.ezplatform.office.forum.service.ForumLabelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 便签管理控制类
 * 2019年11月2日17:40:59
 * @author Administrator
 *
 */
@RestController
@RequestMapping(value="/api/w/forum/label")
public class ForumLabelWebApiController extends BaseController<ForumLabel, String>{
	
	private final Logger LOGGER = LoggerFactory.getLogger(ForumLabelWebApiController.class);

    @Autowired
    private ForumLabelService forumLabelService;

    @Autowired
	private LogService logService;

    @Override
    protected BaseService<ForumLabel, String> getEntityService() {
        return forumLabelService;
    }
    
    /**
     * 初始化数据
     *
     * @param request
     * @param model
     * @param id
     */
    @ModelAttribute
    public void prepareModel(HttpServletRequest request, Model model,
                             @RequestParam(value = "id", required = false) String id) {
        super.initPrepareModel(request, model, id);
    }
    
    /**
     * 获取列表（翻页）数据
     *
     * @param request
     * @return json
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions({"stdForum:label:03"})
    public Page<Map> findByPage(HttpServletRequest request) {
        String corpId = WebUtils.getCurrentUser().getCorpId();
        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
        List<PropertyFilter> filter = PropertyFilter.buildFiltersFromHttpRequest(ForumLabel.class, request);
        Page<Map> page = forumLabelService.findPage(pageable, filter, getToken(), corpId);
        return page;
    }
    
    /**
     * 根据id获取标签信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET) 
    @ResponseBody
    @RequiresPermissions(value = {"stdForum:label:03", "stdForum:label:02"}, logical = Logical.OR)
    public OperationResult editShow(@RequestParam("id") String id,HttpServletRequest request) {
    	String logStatus = request.getParameter("logStatus");
    	ForumLabel label = forumLabelService.findOne(id);
    	if(!StringUtils.equals(logStatus, "1")) {
    		logService.saveModuleLog("forum:label:03", label.getName(), ""); 
        }
        return OperationResult.buildSuccessResult(label);
    }
    
    /**
     * 保存/修改标签
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions(value = {"stdForum:label:01", "stdForum:label:02"}, logical = Logical.OR)
    public OperationResult editSave(@ModelAttribute("entity") ForumLabel entity, HttpServletRequest request, Model model) {
        OperationResult result ;
        if(forumLabelService.checkLabel(entity.getName(),WebUtils.getCurrentUser().getCorpId(),entity.getId())) {
        	Map resources = new HashMap();
        	//国际化资源
    		resources.put("i18NCode", "oa.forum.inhaslabel");
        	result = OperationResult.buildFailureResult("您输入的标签名称已存在",resources);
        }else {
        	if(entity.getId()==null||StringUtils.isBlank(entity.getId())) {
        		logService.saveModuleLog("forum:label:01", entity.getName(), ""); 
        	}else {
                ForumLabel oldLabel = forumLabelService.findOne(entity.getId());
        		logService.saveModuleLog("forum:label:02", oldLabel.getName(), ""); 
        	}
        	 result = super.editSave(entity);
        }
        return result;
    }
    
    /**
     * 删除（批量）数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions({"stdForum:label:04"})
    public OperationResult delete(@RequestParam("ids") String... ids) {
    	Map resources = new HashMap();
    	//国际化资源
		resources.put("i18NCode", "oa.forum.deletetips4");
		forumLabelService.logicDelete(ids);
        return OperationResult.buildSuccessResult("删除成功",resources);
    }
    
    /**
     * 获取所有的标签
     */
    @RequestMapping(value = "/allLabel", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult allLabel(HttpServletRequest request){
    	String corpId = WebUtils.getCurrentUser().getCorpId();
    	String userId=WebUtils.getCurrentUser().getUserId();
    	//标签
    	String userName=WebUtils.getCurrentUser().getUserName();
    	String boardId = request.getParameter("boardId");
    	String isModeratorFlag = request.getParameter("isModerator");
    	List<Map> labelList=forumLabelService.findAllLabel(corpId);
    	boolean isModerator=true;
    	if("0".equals(isModeratorFlag)) {
    		isModerator=false;
    	}
    	if(isModeratorFlag==null) {
    		List<ForumModeratorScope> list=forumLabelService.selectAllModerator(userId,boardId,userName);
        	if(CollectionUtils.isNotEmpty(list)) {
        		isModerator=false;
        	}
        	if("admin".equals(userName)) {
        		isModerator=false;
        	}
    	}
    	Map m=new HashMap();
    	m.put("labelList", labelList);
    	m.put("isModerator", isModerator);
    	return OperationResult.buildSuccessResult(m);
    }
	
}